import type { App } from 'vue';
import { useUserInfo } from '/@/stores/userInfo';

/**
 * 按钮权限指令-无按钮权限不显示
 * @directive 单个按钮权限验证（v-btnPermission="xxx"）
 */
export function btnPermission(app: App) {
  app.directive('btnPermission', {
    mounted(el, binding) {
      const stores = useUserInfo();
      const btnArr = filterPath(stores.userInfos.menus, window.location.hash.slice(1))
      if (!btnArr.find((item: any) => item.name == binding.value)) {
        el.style.display = 'none'
      }
    },
  });
}

function filterPath(tree: any, path: string) {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    // 判断当前节点是否匹配目标路由
    if (node.path == path) {
      // 匹配并返回当前路由地址下的按钮权限列表
      return node.childList;
    } else {
      if (node.childList && node.childList.length > 0) {
        const result: any = filterPath(node.childList, path);
        if (result) {
          return result;
        }
      }
    }
  }
}